package com.xhj.bigfactory.bigFactory.Lock;

import java.util.Random;
import java.util.concurrent.Semaphore;

import static java.lang.System.out;
import static java.lang.Thread.currentThread;

/**
 * -
 *
 * @author 周沫 @Date 2021-07-30 @Time 0:26
 */
public class SemaphoreDemo {

  public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(3);

    for (int i = 0; i < 5; i++) {
      new Thread(
              () -> {
                try {
                  semaphore.acquire();
                } catch (Exception e) {
                  e.printStackTrace();
                } finally {
                }
                out.println(currentThread().getName() + ": come in...");
                int time = new Random().nextInt(1000);
                try {
                  Thread.sleep(time);
                } catch (Exception e) {
                  e.printStackTrace();
                } finally {
                }
                out.println(currentThread().getName() + ": ...leave");
                semaphore.release();
              },
              "t" + i)
          .start();
    }
    out.println("main...");
  }
}
